package 设计模式.单例模式.破坏单例模式;

import 设计模式.单例模式.SingletonEnum;

import java.io.*;
import java.lang.reflect.Constructor;

/**
 * @author : K k
 * @date : 21:13 2020/10/5
 */
public class DestroyDemo1  {

    //破护方式1：通过反射破坏
    public void reflectDestroy() throws Exception{
        //反射获取构造器
        Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();
        constructor.setAccessible(true);

        //破坏单例模式
        Singleton singleton1=Singleton.getSingleton();
        Singleton singleton2=Singleton.getSingleton();
        Singleton singleton3=constructor.newInstance();

        System.out.println("singleton1:"+singleton1.hashCode()+" singleton2:"+singleton2.hashCode()
                +" singleton3:" + singleton3.hashCode());
    }

    //破护方式2：通过反序列化破坏
    public void serializableDestroy() throws Exception{
        Singleton singleton1=Singleton.getSingleton();
        Singleton singleton2=Singleton.getSingleton();

        //通过反序列化的方式
        ByteArrayOutputStream os=new ByteArrayOutputStream();
        ObjectOutputStream oos=new ObjectOutputStream(os);
        oos.writeObject(singleton1);
        oos.flush();
        ByteArrayInputStream is=new ByteArrayInputStream(os.toByteArray());
        ObjectInputStream ois=new ObjectInputStream(is);
        Singleton singleton3 = (Singleton)ois.readObject();

        System.out.println("singleton1:"+singleton1.hashCode()+" singleton2:"+singleton2.hashCode()
                +" singleton3:" + singleton3.hashCode());
    }

    //通过枚举类获得
    public void enumSingleton() throws Exception {
        SingletonEnum singleton1 = SingletonEnum.singleton;
        SingletonEnum singleton2 = SingletonEnum.singleton;
        SingletonEnum singleton3 = SingletonEnum.singleton;
        //反射获取构造器
        /*Constructor<SingletonEnum> constructor = SingletonEnum.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        SingletonEnum singleton3= constructor.newInstance();*/
        System.out.println("singleton1:"+singleton1.hashCode()+" singleton2:"+singleton2.hashCode()
                +" singleton3:" + singleton3.hashCode() );
        singleton1.action();
    }

    public static void main(String[] args) throws Exception{
        DestroyDemo1 destroyDemo1=new DestroyDemo1();
        //destroyDemo1.reflectDestroy();
        destroyDemo1.serializableDestroy();
        //destroyDemo1.enumSingleton();
    }
}
